/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.borrow.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.dto.borrow.BorrowExcelDTO;
import com.fuyao.cloud.asset.dto.borrow.BorrowSearchDTO;
import com.fuyao.cloud.asset.entity.receive.Receive;
import com.fuyao.cloud.asset.enums.AssetStatusEnum;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.controller.FlowableController;
import com.fuyao.cloud.common.core.flowable.enums.ProcessStatusEnum;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.entity.borrow.Borrow;
import com.fuyao.cloud.asset.borrow.service.BorrowService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 借用&归还表
 *
 * @author ly
 * @date 2022-01-06 10:37:40
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/borrow" )
@Api(value = "borrow", tags = "借用&归还表管理")
public class BorrowController implements FlowableController {

    private final BorrowService borrowService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param borrow 借用&归还表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('borrow_borrow_view')" )
    public R getBorrowPage(Page page, BorrowSearchDTO borrow) {
        return R.ok(borrowService.page(page, SpliceQueryWrapper.spliceSearchCondition(borrow),borrow));
    }


    /**
     * 通过id查询借用&归还表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('borrow_borrow_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(borrowService.getById(id));
    }

    /**
     * 新增借用&归还表
     * @param borrow 借用&归还表
     * @return R
     */
    @ApiOperation(value = "新增借用&归还表", notes = "新增借用&归还表")
    @SysLog("新增借用&归还表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('borrow_borrow_add')" )
    public R save(@RequestBody Borrow borrow) {
        borrowService.save(borrow);
        return R.ok(borrow);
    }

    /**
     * 修改借用&归还表
     * @param borrow 借用&归还表
     * @return R
     */
    @ApiOperation(value = "修改借用&归还表", notes = "修改借用&归还表")
    @SysLog("修改借用&归还表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('borrow_borrow_edit')" )
    public R updateById(@RequestBody Borrow borrow) {
        return R.ok(borrowService.updateById(borrow));
    }

    /**
     * 通过id删除借用&归还表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除借用&归还表", notes = "通过id删除借用&归还表")
    @SysLog("通过id删除借用&归还表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('borrow_borrow_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(borrowService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param borrow 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('borrow_borrow_export')" )
    public List<BorrowExcelDTO> export(BorrowSearchDTO borrow) {
        return borrowService.listBorrow(SpliceQueryWrapper.spliceSearchCondition(borrow));
    }


	@GetMapping("/create")
	@PreAuthorize("@pms.hasPermission('borrow_borrow_add')")
	public R create() {
		return R.ok(this.borrowService.create());
	}

	@GetMapping("/edit/{id}")
	@PreAuthorize("@pms.hasPermission('borrow_borrow_edit')")
	public R edit(@PathVariable("id") Long id) {
		return R.ok(this.borrowService.edit(id));
	}

	@GetMapping("/remand")
	public R remand(@RequestParam("ids") Long[] ids) {
		return R.ok(this.borrowService.updateRemand(Arrays.asList(ids)),"归还成功");
	}


    @ApiOperation(value = "批量删除借用&归还", notes = "批量删除借用&归还")
    @SysLog("批量删除借用&归还" )
    @DeleteMapping("/batchDelete" )
    @PreAuthorize("@pms.hasPermission('borrow_borrow_del')" )
    public R batchDelete(@RequestBody List<Long> ids) {
        return borrowService.batchDelete(ids);
    }

    @ApiOperation(value = "起草环节结束回调方法", notes = "起草环节结束回调方法")
    @PostMapping(value = "/draftEndCallback", produces = "application/json")
    @Override
    public R draftEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            Borrow  borrow = this.borrowService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(borrow), String.format("未找到对应的业务数据：%s", id));
            borrow.setStatus(AssetStatusEnum.PROCESSING.getCode());
            this.borrowService.approval(borrow);
            return R.ok(borrow,"修改状态成功");
        }
        return R.ok(CommonConstants.SUCCESS,"起草环节结束回调方法");
    }

    @ApiOperation(value = "回退至起草环节回调方法", notes = "回退至起草环节回调方法")
    @PostMapping(value = "/returnCallback", produces = "application/json")
    @Override
    public R returnCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            Borrow  borrow = this.borrowService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(borrow), String.format("未找到对应的业务数据：%s", id));
            borrow.setStatus(AssetStatusEnum.DRAFT.getCode());
            this.borrowService.approval(borrow);
            return R.ok(borrow,"修改状态成功");
        }
        return R.ok(CommonConstants.SUCCESS,"回退至起草环节回调方法");
    }

    @ApiOperation(value = "流程结束回调方法", notes = "流程结束回调方法")
    @PostMapping(value = "/callback", produces = "application/json")
    @Override
    public R finishEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            Borrow  borrow = this.borrowService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(borrow), String.format("未找到对应的业务数据：%s", id));
            String status = params.containsKey(ProcessStatusEnum.ZZ.toString()) ? AssetStatusEnum.INVALID.getCode() : AssetStatusEnum.APPROVE.getCode();
            borrow.setStatus(status);
            this.borrowService.approval(borrow);
            return R.ok(borrow,"修改状态成功");
        }
        return R.failed("未找到对应的业务数据");
    }
}
